package com.csoa.community.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.csoa.community.R;
import com.csoa.community.bean.AttachBean;
import com.csoa.community.bean.RiChengModel;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.requests.AbstractRequest;
import com.csoa.community.requests.ComDownAttachRequest;
import com.csoa.community.requests.RiChengXQRequest;
import com.csoa.community.requests.TongzhiAttachRequest;
import com.csoa.community.services.UpgradeService;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.widget.PullToRefreshScrollView;
import com.csoa.community.widget.PullToRefreshBase.OnRefreshListener;

public class RiChengXQActivity extends BaseActivity implements OnClickListener {

	public static final String extra_tongzhi = "extra_tongzhi";
	public static final String extra_position = "extra_position";

	private static Map<String, RiChengModel> contents;

	ProgressBar mProgress;
	TextView title;
	TextView time;
	TextView content;
	TextView zuozhe;

	int preCount = 0;
	RiChengModel model;
	int position;
	private LinearLayout mTongzhiAttachTipLayout;
	private LinearLayout mTongzhiAttachLayout;
	private ScrollView scroll;
	private PullToRefreshScrollView mPullScroll;
	private LayoutInflater inflater;
	private View mScollerContentView;

	@Override
	public void initUI() {
		setContentView(R.layout.richeng_xq);

		mPullScroll = (PullToRefreshScrollView) this
				.findViewById(R.id.zhoujiScrollView);
		mPullScroll.setMode(PullToRefreshScrollView.MODE_PULL_DOWN_TO_REFRESH);
		mPullScroll.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				buildRequestGetRiCheng();
			}
		});
		scroll = mPullScroll.getRefreshableView();
		inflater = LayoutInflater.from(this);
		mScollerContentView = inflater.inflate(R.layout.common_xq_scroller,
				null);
		scroll.addView(mScollerContentView);

		// scroll = (ScrollView) this.findViewById(R.id.zhoujiScrollView);
		// 附件layout（包括附件的标题）
		mTongzhiAttachTipLayout = (LinearLayout) this
				.findViewById(R.id.tongzhiAttachTipLayout);

		// 附件layout
		mTongzhiAttachLayout = (LinearLayout) this
				.findViewById(R.id.tongzhiAttachLayout);

		this.findViewById(R.id.tzx_btn_pre).setOnClickListener(this);
		this.findViewById(R.id.tzx_btn_next).setOnClickListener(this);

		title = (TextView) this.findViewById(R.id.tzx_title);
		time = (TextView) this.findViewById(R.id.tzx_time);
		content = (TextView) this.findViewById(R.id.tzx_content);
		zuozhe = (TextView) this.findViewById(R.id.tzx_zuozhe);
		mProgress = (ProgressBar) this.findViewById(R.id.tzx_progress);

		content.setMovementMethod(ScrollingMovementMethod.getInstance());

		super.initUI();
	}

	@Override
	public void initData() {
		model = (RiChengModel) getIntent().getSerializableExtra(extra_tongzhi);
		position = getIntent().getIntExtra(extra_position, 0);

		if (contents == null) {
			contents = new HashMap<String, RiChengModel>();
		}

		title.setText(model.name);
		time.setText(getTimeString());

		if (!contents.containsKey(model.id)) {
			buildRequestGetRiCheng();
		} else {
			initCenterUI(true);
			model = contents.get(model.id);
			initText();
		}
		super.initData();
	}

	@Override
	public void onClick(View v) {
		scroll.scrollTo(0, 0);
		switch (v.getId()) {
		case R.id.tzx_btn_pre:
			if (position == 0) {
				showToast("没有更多日程记录了.");
				return;
			}
			stopTask();
			model = RiChengActivity.data.get(position - 1);
			title.setText(model.name);
			time.setText(getTimeString());
			zuozhe.setText("");
			position--;
			if (contents.containsKey(model.id)) {
				initCenterUI(true);
				model = contents.get(model.id);
				initText();
			} else {
				buildRequestGetRiCheng();
			}
			content.scrollTo(0, 0);
			break;
		case R.id.tzx_btn_next:
			if (position == (RiChengActivity.data.size() - 1)) {
				showToast("没有更多日程记录了.");
				return;
			}
			stopTask();
			model = RiChengActivity.data.get(position + 1);
			title.setText(model.name);
			time.setText(getTimeString());
			zuozhe.setText("");
			position++;
			if (contents.containsKey(model.id)) {
				initCenterUI(true);
				model = contents.get(model.id);
				initText();
			} else {
				buildRequestGetRiCheng();
			}
			content.scrollTo(0, 0);
			break;
		default:
			break;
		}
	}

	public void initText() {
		title.setText(model.name);
		time.setText(getTimeString());
		if (StringUtils.isNotEmpty(model.zuozhe)) {
			zuozhe.setText(model.zuozhe);
		}
		content.setText("");
		if (StringUtils.isNotEmpty(model.content)) {
			content.setText(Html.fromHtml(model.content));
		} else {
			content.setText("暂无正文信息");
		}
		setDataToAttachView(model.attachs);
	}

	private String getTimeString() {
		String str = "";
		try {
			str = "开始时间:"
					+ (new SimpleDateFormat("yyyy-MM-dd HH:mm")
							.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
									.parse(model.time_start)))
					+ "\n结束时间:"
					+ (new SimpleDateFormat("yyyy-MM-dd HH:mm")
							.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
									.parse(model.time_end)));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return str;
	}

	protected void buildRequestGetRiCheng() {
		mTongzhiAttachTipLayout.setVisibility(View.GONE);
		initCenterUI(false);
		mPullScroll.showHeadView();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("EventID", model.id));
		netRequestGetRiCheng(new RiChengXQRequest(params));
	}

	WcfAsyncTask task;

	private void netRequestGetRiCheng(AbstractRequest request) {
		stopTask();
		task = new WcfAsyncTask(this, new OnUICallback() {
			@Override
			public void onGetResult(AbstractRequest request) {
				initCenterUI(true);
				mPullScroll.onRefreshComplete();
				RiChengXQRequest mRq = (RiChengXQRequest) request;
				if (mRq.model != null) {
					contents.remove(model.id);
					contents.put(model.id, mRq.model);
					model = mRq.model;
					initText();
					buildAttachRequest(model.id);
				}
			}

			@Override
			public void onCancel() {
				initCenterUI(true);
				mPullScroll.onRefreshComplete();
			}

			@Override
			public void onProgress(int progress, String msg) {
				RiChengXQActivity.this.showToast(msg);
			}
		});
		task.execute(request);
	}

	private void stopTask() {
		if (task != null) {
			task.cancel(true);
		}
	}

	/**
	 * 下载附件构建Request
	 * 
	 * @param request
	 */
	protected void buildAttachRequest(String DocumentID) {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("DocumentID", DocumentID));
		netRequestAttach(new TongzhiAttachRequest(params));
	}

	/**
	 * 下载附件
	 * 
	 * @param request
	 */
	private void netRequestAttach(TongzhiAttachRequest request) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onCancel() {

			}

			@Override
			public void onProgress(int progress, String msg) {
				RiChengXQActivity.this.showToast(msg);
			}

			@Override
			public void onGetResult(AbstractRequest result) {
				TongzhiAttachRequest attachRequest = (TongzhiAttachRequest) result;
				if (attachRequest.mAttachs != null) {
					model.attachs = attachRequest.mAttachs;
					setDataToAttachView(attachRequest.mAttachs);
				}
			}
		}).execute(request);
	}

	/**
	 * 附件下载完毕之后显示在界面中
	 * 
	 * @param mAttachs
	 */
	protected void setDataToAttachView(List<AttachBean> mAttachs) {
		mTongzhiAttachLayout.removeAllViews();
		if (mAttachs == null || mAttachs.size() == 0) {
			mTongzhiAttachTipLayout.setVisibility(View.GONE);
			return;
		}
		mTongzhiAttachTipLayout.setVisibility(View.VISIBLE);

		for (int i = 0; i < mAttachs.size(); i++) {
			final AttachBean attach = mAttachs.get(i);
			TextView text = new TextView(this);
			text.setText("附件" + (i + 1) + ":" + attach.FileName);
			text.setTextSize(18);
			text.setTextColor(this.getResources().getColor(R.color.attach));
			text.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					boolean isAttachExists = GlobalVars.getInst()
							.isAttachExists(getApplicationContext(),
									attach.FileName);

					if (!isAttachExists) {

						if (!AndroidUtils
								.isNetworkValidate(RiChengXQActivity.this)) {
							RiChengXQActivity.this
									.showToast("无法检测到网络,检查网络是否开启");
							return;
						}
						buildDownLoadAttachRequest(attach);
					}

				}
			});
			mTongzhiAttachLayout.addView(text);
		}
	}

	protected void buildDownLoadAttachRequest(AttachBean attach) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("AttachID", attach.AttachID));
		params.add(new BasicNameValuePair("FileType", attach.FileExtend));
		netRequestDownAttach(new ComDownAttachRequest(params), attach);
	}

	private void netRequestDownAttach(ComDownAttachRequest request,
			final AttachBean attach) {

		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				ComDownAttachRequest downAttachRequest = (ComDownAttachRequest) request;
				if (!StringUtils.isEmpty(downAttachRequest.success)
						&& "1".equals(downAttachRequest.success)) {

					RiChengXQActivity.this
							.showToast("附件后台下载中...,下载完成自动存入CSOA目录中");
					startService(attach);
				} else {
					RiChengXQActivity.this.showToast("获取附件失败,附件可能已经删除");
				}
			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				RiChengXQActivity.this.showToast(msg);
			}
		}).execute(request);

	}

	private void startService(AttachBean attach) {

		Intent intent = new Intent();
		intent.setClass(this, UpgradeService.class);
		intent.putExtra("AttachID", attach.AttachID);
		intent.putExtra("FileExtend", attach.FileExtend);
		intent.putExtra("FileName", attach.FileName);
		this.startService(intent);
	}

	private void initCenterUI(boolean isShowList) {
		if (isShowList) {
			if (content.getVisibility() != View.VISIBLE) {
				content.setVisibility(View.VISIBLE);
			}
			if (mProgress.getVisibility() != View.INVISIBLE) {
				mProgress.setVisibility(View.INVISIBLE);
			}
		} else {
			if (content.getVisibility() != View.INVISIBLE) {
				content.setVisibility(View.INVISIBLE);
			}
			if (mProgress.getVisibility() != View.VISIBLE) {
				mProgress.setVisibility(View.VISIBLE);
			}
		}
	}

}
